package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.FeeKey;
import com.atguigu.lease.model.entity.FeeValue;
import com.atguigu.lease.web.admin.service.FeeKeyService;
import com.atguigu.lease.web.admin.service.FeeValueService;
import com.atguigu.lease.web.admin.vo.fee.FeeKeyVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@Tag(name = "房间杂费管理")
@RestController
@RequestMapping("/admin/fee")
public class FeeController {

    // 杂费名称业务组件
    @Autowired
    private FeeKeyService feeKeyService;

    // 杂费值业务组件
    @Autowired
    private FeeValueService feeValueService;


    @Operation(summary = "保存或更新杂费名称")
    @PostMapping("key/saveOrUpdate")
    public Result saveOrUpdateFeeKey(@RequestBody FeeKey feeKey) {
        feeKeyService.saveOrUpdate(feeKey);
        return Result.ok();
    }

    @Operation(summary = "保存或更新杂费值")
    @PostMapping("value/saveOrUpdate")
    public Result saveOrUpdateFeeValue(@RequestBody FeeValue feeValue) {

        feeValueService.saveOrUpdate(feeValue);
        return Result.ok();
    }


    @Operation(summary = "查询全部杂费名称和杂费值列表")
    @GetMapping("list")
    public Result<List<FeeKeyVo>> feeInfoList() {

        // 方法一：通过Java代码实现，具体代码在  feeKeyService 实现类中
       // List<FeeKeyVo> feeKeyVoList = feeKeyService.getFeeKeyVoList();


        // 方法二： 通过关联查询实现

       // List<FeeKeyVo> feeKeyVoList  =  feeKeyService.getFeeKeyVoList1();

        // 方法三： 通过分步查询实现
        List<FeeKeyVo> feeKeyVoList  =  feeKeyService.getFeeKeyVoList2();

        return Result.ok(feeKeyVoList);
    }

    @Operation(summary = "根据id删除杂费名称")
    @DeleteMapping("key/deleteById")
    public Result deleteFeeKeyById(@RequestParam Long feeKeyId) {

        List<FeeValue> feeValueList = feeValueService.list(new LambdaQueryWrapper<FeeValue>().eq(FeeValue::getFeeKeyId, feeKeyId));

        // 这里批量删除的时候，要传入的是一个ID的集合，而上面是一个 feeValueList 所有里面可以使用流式操作,专门获取 feeKeyId 得到新集合
        // map 里面原始的写法 map( feevalue -> {return feeValue.getFeeKeyId();}} )  传入的参数为 feeValue  返回的值为 feeKeyId
        feeValueService.removeBatchByIds(feeValueList.stream().map(FeeValue::getId).collect(Collectors.toList()));

        feeKeyService.removeById(feeKeyId);

        return Result.ok();

    }

    @Operation(summary = "根据id删除杂费值")
    @DeleteMapping("value/deleteById")
    public Result deleteFeeValueById(@RequestParam Long id) {

        feeValueService.removeById(id);
        return Result.ok();
    }
}
